package Page.BookBorrowingRecordPage;

import Navigation.NavigationController;
import Dao.BookBorrowingRecordDao;
import DataClass.BookBorrowingRequestRecord;
import Page.DetailPage.DetailPage;
import Page.DetailPage.DetailPageViewModel;
import Setting.Setting;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.Modality;
import javafx.stage.Stage;

import java.net.URL;
import java.sql.SQLException;
import java.sql.Time;
import java.util.ArrayList;
import java.util.ResourceBundle;

/**
 * @since 2024-06-02
 * @author yooo_fan
 */
public class BookBorrowingRecordController implements Initializable {
    @FXML
    public TextField InputFindBook;
    @FXML
    public Button FindButton;
    @FXML
    public Button ClearButton;
    @FXML
    public TextField InputFindPeople;
    @FXML
    public Button RefreshButton;
    @FXML
    public javafx.scene.control.Pagination Pagination;
    @FXML
    private Button AddButton;
    @FXML
    private Button BackButton;
    @FXML
    private TableView<BookBorrowingRequestRecord> BookBorrowingRecordTable;

    @FXML
    private TableColumn<BookBorrowingRequestRecord,Integer> rid;
    @FXML
    private TableColumn<BookBorrowingRequestRecord,String> rBookId;
    @FXML
    private TableColumn<BookBorrowingRequestRecord,String> rRecordId;
    @FXML
    private TableColumn<BookBorrowingRequestRecord,Time> rTime;
    @FXML
    private TableColumn<BookBorrowingRequestRecord,String> rPeople;
    @FXML
    private TableColumn<BookBorrowingRequestRecord,String> rbName;

    // viewModel
    private BookBorrowingRecordViewModel viewModel;

    // 每一页数据数量
    private final static int rowsPerPage = Setting.ItemsPerPage;

    //=========================================================================================================
    // init

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        viewModel = new BookBorrowingRecordViewModel();

        rid.setCellValueFactory(new PropertyValueFactory<>("rid"));
        rBookId.setCellValueFactory(new PropertyValueFactory<>("rBookId"));
        rRecordId.setCellValueFactory(new PropertyValueFactory<>("rRecordId"));
        rTime.setCellValueFactory(new PropertyValueFactory<>("rTime"));
        rPeople.setCellValueFactory(new PropertyValueFactory<>("rPeople"));
        rbName.setCellValueFactory(new PropertyValueFactory<>("rbName"));

        // 绑定
        InputFindBook.textProperty().bindBidirectional(viewModel.getInputBookName());
        InputFindPeople.textProperty().bindBidirectional(viewModel.getInputPeopleName());
        try {
            // 从数据库或其他来源获取数据
            viewModel.setDataList(BookBorrowingRecordDao.getBookBorrowingRequestRecord());
        } catch (SQLException e) {
            viewModel.setDataList(new ArrayList<>());
            System.err.println("BookBorrowingRecord 数据获取失败 in BookBorrowingRecordController");
        }

        // 初始化分页器具
        this.initPagination();

        // 加入监听器
        InputFindBook.textProperty().addListener((observable, oldValue, newValue) -> {
            viewModel.updateInputBookName(newValue);
        });
        InputFindPeople.textProperty().addListener((observable, oldValue, newValue) -> {
            viewModel.updateInputPeopleName(newValue);
        });
        viewModel.getDataListProperty().addListener((observable, oldValue, newValue) -> {
            this.refreshPagination();
        });
        BookBorrowingRecordTable.setOnMouseClicked(event ->
        {
            if(event.getClickCount() == 2)
            {
                BookBorrowingRequestRecord data = BookBorrowingRecordTable.getSelectionModel().getSelectedItem();
                System.out.println(data.getRBookId()+data.getRPeople()+data.getRbName());
                showDetail();
            }
        });
    }

    //=========================================================================================================
    // Paginationr

    private void initPagination(){
        this.refreshPagination();
    }
    /**
     * @since 2024-06-04
     * @param pageIndex 当前页面索引
     * @return TableView
     */
    private TableView<BookBorrowingRequestRecord> createPage(int pageIndex) {
        int lastIndex = Math.min(pageIndex * rowsPerPage + rowsPerPage, viewModel.getDataListProperty().size());
        int displace = pageIndex * rowsPerPage;
        ObservableList<BookBorrowingRequestRecord> pageData = FXCollections.observableArrayList(viewModel.getDataListProperty().subList(displace, lastIndex));

        BookBorrowingRecordTable.setItems(pageData);
        return BookBorrowingRecordTable;
    }

    /**
     * 重载分页器
     */
    public void refreshPagination(){
        Pagination.setPageCount((viewModel.getDataListProperty().size()/rowsPerPage +1 ));
        Pagination.setPageFactory(this::createPage);
        Pagination.setCurrentPageIndex(0);
    }

    //=========================================================================================================
    // Click Event

    public void backButtonClicked(javafx.event.ActionEvent actionEvent) {
        viewModel.backButtonClicked();
    }

    public void addButtonClicked(javafx.event.ActionEvent actionEvent) {
        viewModel.addButtonClicked();
    }

    public void findButtonClicked(javafx.event.ActionEvent actionEvent) {
        viewModel.clickFindButton();
    }

    // 刷新表格
    public void refreshButtonClicked(javafx.event.ActionEvent actionEvent) {
        viewModel.refresh();
        try {
            // 从数据库或其他来源获取数据
            viewModel.setDataList(BookBorrowingRecordDao.getBookBorrowingRequestRecord());
        } catch (SQLException e) {
            viewModel.setDataList(new ArrayList<>());
            System.err.println("BookBorrowingRecord 数据获取失败" + e.getMessage());
        }
    }

    public void clearButtonClicked(ActionEvent actionEvent) {
        viewModel.clearFilter();
    }

    //========================================================================================================
    public void showDetail()
    {
        Stage stage = new Stage();
        stage.setTitle("详情页面");
        DetailPage detailPage = new DetailPage();
        stage.setScene(detailPage.getScene());
        stage.initOwner(NavigationController.getLastScene().getWindow());
        stage.initModality(Modality.WINDOW_MODAL);
        DetailPageViewModel.getViewModel().setTitle("这是一个标题");
        stage.showAndWait();
    }

}